package com.es.service.impl;

import com.es.domain.EsMetaResult;
import com.es.domain.Student;
import com.es.entity.StudentDO;
import com.es.mapper.StudentMapper;
import com.es.service.StudentServiceI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述:
 * es-meta-
 *
 * @author Derek
 * @create 2021-11-30 10:37
 */
@Service
public class StudentServiceImpl implements StudentServiceI {
    @Autowired
    private StudentMapper mapper;


    @Override
    public EsMetaResult<List<Student>> list() {
        List<StudentDO> doList = mapper.list();
        List<Student> list = new ArrayList<>();
        doList.forEach(e->{
            Student s = new Student();
            BeanUtils.copyProperties(e,s);
            list.add(s);
        });
        EsMetaResult<List<Student>> esMetaResult = EsMetaResult.success(list);
        return esMetaResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EsMetaResult<String> save(Student student) {
        if(student == null){
           return EsMetaResult.fail();
        }
        StudentDO studentDO = new StudentDO();
        BeanUtils.copyProperties(student, studentDO);
        int i = mapper.save(studentDO);
        if(i>0){
            return EsMetaResult.success("保存成功");
        }
        return EsMetaResult.fail();
    }

    @Override
    public EsMetaResult<Student> getById(Integer id) {
        //验证数据有效性

        StudentDO studentDO = mapper.get(id);
        if(studentDO != null) {
            //
            Student student = new Student();
            BeanUtils.copyProperties(studentDO, student);
            return EsMetaResult.success(student);
        }
        return EsMetaResult.fail("没有此学生信息");
    }
}
